package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private ClazzService clazzService;

    @GetMapping
    //分页查询，其实应该放到service层的，这里懒得改了
    public Result list(StudentQueryParam student) {
        log.info("查询所有学生信息：{}", student);
        Page<Student> studentPage = new Page<>(student.getPage(), student.getPageSize());
        studentPage.addOrder(OrderItem.desc("update_time"));
        LambdaQueryWrapper<Student> slw = new LambdaQueryWrapper<>();
        slw.like(student.getName() != null && student.getName().length() > 0, Student::getName, student.getName());
        slw.eq(student.getDegree() != null, Student::getDegree, student.getDegree());
        slw.eq(student.getClazzId() != null, Student::getClazzId, student.getClazzId());
        Page<Student> page = studentService.page(studentPage, slw);
        //结果集合中还要添加对应的班级
        List<Student> list = page.getRecords();
        Set<Integer> clazzIdSet = list.stream().map(Student::getClazzId).collect(Collectors.toSet());
        if(clazzIdSet.size() > 0){ //有班级数据需要处理
            List<Clazz> clazzList =clazzService.listByIds(clazzIdSet);
            //接下来需要封装Map,将班级id和班级名称对应起来
            Map<Integer, String> ClazzMap = clazzList.stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));
            for (Student emp : list) {
                emp.setClazzName(ClazzMap.get(emp.getClazzId()));
            }
        }
        PageResult<Student> result = new PageResult<>(page.getTotal(), list);
        return Result.success(result);
    }

    @PostMapping
    public Result save(@RequestBody Student student) {
        log.info("新增学生信息：{}", student);
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentService.save(student);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询学生信息：{}", id);
        Student res = studentService.getById(id);
        return Result.success(res);
    }

    @PutMapping
    public Result update(@RequestBody Student student) {
        log.info("修改学生信息：{}", student);
        student.setUpdateTime(LocalDateTime.now());
        studentService.updateById(student);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("根据id删除学生信息：{}", ids);
        studentService.removeByIds(ids);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    @Transactional(rollbackFor = Exception.class)
    public Result violation(@PathVariable Integer id, @PathVariable Integer score) {
        log.info("根据id{}扣分, 扣分：{}", id, score);
        studentService.violation(id, score);

        return Result.success();
    }
}
